<template>
  <div class="statistics-container">
    <div class="page-header">
      <h1>学习统计</h1>
      <p>学习数据分析与报告</p>
    </div>
    
    <div class="statistics-content">
      <div class="statistics-filters">
        <div class="filter-options">
          <el-select v-model="timeRange" placeholder="时间范围">
            <el-option label="本周" value="week"></el-option>
            <el-option label="本月" value="month"></el-option>
            <el-option label="本学期" value="semester"></el-option>
            <el-option label="全部" value="all"></el-option>
          </el-select>
          
          <el-select v-model="subjectFilter" placeholder="学科" clearable>
            <el-option 
              v-for="subject in subjects" 
              :key="subject.id" 
              :label="subject.name" 
              :value="subject.id"
            ></el-option>
          </el-select>
        </div>
      </div>
      
      <div class="statistics-overview">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="6">
            <el-card class="stat-card">
              <div class="stat-icon" style="background-color: #409EFF;">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">学习时长</div>
                <div class="stat-value">{{ formatTime(studyTimeTotal) }}</div>
                <div class="stat-trend" :class="studyTimeTrend > 0 ? 'up' : studyTimeTrend < 0 ? 'down' : ''">
                  <el-icon v-if="studyTimeTrend > 0"><ArrowUp /></el-icon>
                  <el-icon v-else-if="studyTimeTrend < 0"><ArrowDown /></el-icon>
                  <span>{{ Math.abs(studyTimeTrend) }}%</span>
                </div>
              </div>
            </el-card>
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="6">
            <el-card class="stat-card">
              <div class="stat-icon" style="background-color: #67C23A;">
                <el-icon><Finished /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">完成任务</div>
                <div class="stat-value">{{ completedTasks }}</div>
                <div class="stat-trend" :class="tasksTrend > 0 ? 'up' : tasksTrend < 0 ? 'down' : ''">
                  <el-icon v-if="tasksTrend > 0"><ArrowUp /></el-icon>
                  <el-icon v-else-if="tasksTrend < 0"><ArrowDown /></el-icon>
                  <span>{{ Math.abs(tasksTrend) }}%</span>
                </div>
              </div>
            </el-card>
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="6">
            <el-card class="stat-card">
              <div class="stat-icon" style="background-color: #E6A23C;">
                <el-icon><DataAnalysis /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">平均分数</div>
                <div class="stat-value">{{ averageScore }}</div>
                <div class="stat-trend" :class="scoreTrend > 0 ? 'up' : scoreTrend < 0 ? 'down' : ''">
                  <el-icon v-if="scoreTrend > 0"><ArrowUp /></el-icon>
                  <el-icon v-else-if="scoreTrend < 0"><ArrowDown /></el-icon>
                  <span>{{ Math.abs(scoreTrend) }}%</span>
                </div>
              </div>
            </el-card>
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="6">
            <el-card class="stat-card">
              <div class="stat-icon" style="background-color: #F56C6C;">
                <el-icon><Document /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">错题数量</div>
                <div class="stat-value">{{ mistakesCount }}</div>
                <div class="stat-trend" :class="mistakesTrend > 0 ? 'down' : mistakesTrend < 0 ? 'up' : ''">
                  <el-icon v-if="mistakesTrend > 0"><ArrowUp /></el-icon>
                  <el-icon v-else-if="mistakesTrend < 0"><ArrowDown /></el-icon>
                  <span>{{ Math.abs(mistakesTrend) }}%</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      
      <div class="statistics-charts">
        <el-row :gutter="20">
          <el-col :xs="24" :lg="12">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <h3>学习时长分布</h3>
                </div>
              </template>
              <div class="chart-container" ref="studyTimeChart"></div>
            </el-card>
          </el-col>
          
          <el-col :xs="24" :lg="12">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <h3>学科分数对比</h3>
                </div>
              </template>
              <div class="chart-container" ref="scoreChart"></div>
            </el-card>
          </el-col>
          
          <el-col :xs="24" :lg="12">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <h3>学习进度</h3>
                </div>
              </template>
              <div class="chart-container" ref="progressChart"></div>
            </el-card>
          </el-col>
          
          <el-col :xs="24" :lg="12">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <h3>错题分布</h3>
                </div>
              </template>
              <div class="chart-container" ref="mistakesChart"></div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      
      <div class="statistics-details">
        <el-card>
          <template #header>
            <div class="details-header">
              <h3>学习详情记录</h3>
              <el-button type="primary" size="small" @click="exportData">
                <el-icon><Download /></el-icon> 导出数据
              </el-button>
            </div>
          </template>
          
          <el-table :data="studyRecords" style="width: 100%" border>
            <el-table-column prop="date" label="日期" width="120"></el-table-column>
            <el-table-column prop="subject" label="学科" width="100"></el-table-column>
            <el-table-column prop="content" label="学习内容"></el-table-column>
            <el-table-column prop="duration" label="时长" width="100">
              <template #default="scope">
                {{ formatTime(scope.row.duration) }}
              </template>
            </el-table-column>
            <el-table-column prop="score" label="得分" width="80">
              <template #default="scope">
                <span :class="scope.row.score >= 80 ? 'text-success' : scope.row.score >= 60 ? 'text-warning' : 'text-danger'">
                  {{ scope.row.score }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.status === '已完成' ? 'success' : 'info'">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="pagination-container">
            <el-pagination
              background
              layout="prev, pager, next"
              :total="totalRecords"
              :page-size="pageSize"
              :current-page="currentPage"
              @current-change="handlePageChange"
            ></el-pagination>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { 
  Clock, 
  Finished, 
  DataAnalysis, 
  Document, 
  ArrowUp, 
  ArrowDown,
  Download
} from '@element-plus/icons-vue';
import * as echarts from 'echarts/core';
import { 
  BarChart,
  LineChart,
  PieChart,
  RadarChart
} from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

// 注册必要的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  BarChart,
  LineChart,
  PieChart,
  RadarChart,
  CanvasRenderer
]);

// 学科列表
const subjects = [
  { id: 1, name: '数学' },
  { id: 2, name: '物理' },
  { id: 3, name: '化学' },
  { id: 4, name: '语文' },
  { id: 5, name: '英语' },
  { id: 6, name: '历史' },
  { id: 7, name: '地理' },
  { id: 8, name: '生物' }
];

// 状态变量
const timeRange = ref('week');
const subjectFilter = ref('');
const studyTimeTotal = ref(3600 * 25); // 示例：25小时
const studyTimeTrend = ref(15); // 示例：上升15%
const completedTasks = ref(42);
const tasksTrend = ref(8);
const averageScore = ref(85);
const scoreTrend = ref(-3);
const mistakesCount = ref(18);
const mistakesTrend = ref(-12);

// 图表引用
const studyTimeChart = ref(null);
const scoreChart = ref(null);
const progressChart = ref(null);
const mistakesChart = ref(null);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const totalRecords = ref(100);

// 学习记录数据
const studyRecords = ref([
  { date: '2023-07-01', subject: '数学', content: '函数与导数', duration: 3600, score: 92, status: '已完成' },
  { date: '2023-07-02', subject: '物理', content: '力学基础', duration: 2700, score: 85, status: '已完成' },
  { date: '2023-07-03', subject: '化学', content: '有机化学', duration: 3200, score: 78, status: '已完成' },
  { date: '2023-07-04', subject: '语文', content: '现代文阅读', duration: 1800, score: 88, status: '已完成' },
  { date: '2023-07-05', subject: '英语', content: '完形填空', duration: 2400, score: 76, status: '已完成' },
  { date: '2023-07-06', subject: '数学', content: '概率统计', duration: 3000, score: 90, status: '已完成' },
  { date: '2023-07-07', subject: '物理', content: '电磁学', duration: 2500, score: 82, status: '已完成' },
  { date: '2023-07-08', subject: '化学', content: '化学平衡', duration: 2800, score: 75, status: '已完成' },
  { date: '2023-07-09', subject: '语文', content: '古文阅读', duration: 2000, score: 80, status: '已完成' },
  { date: '2023-07-10', subject: '英语', content: '阅读理解', duration: 2200, score: 85, status: '已完成' }
]);

// 格式化时间
const formatTime = (seconds) => {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  
  if (hours > 0) {
    return `${hours}小时${minutes > 0 ? minutes + '分钟' : ''}`;
  } else {
    return `${minutes}分钟`;
  }
};

// 处理页面变化
const handlePageChange = (page) => {
  currentPage.value = page;
  // 这里应该加载对应页的数据
};

// 导出数据
const exportData = () => {
  // 实现导出功能
  console.log('导出数据');
};

// 初始化图表
const initCharts = () => {
  // 学习时长分布图表
  const timeChartInstance = echarts.init(studyTimeChart.value);
  timeChartInstance.setOption({
    title: {
      text: '每日学习时长',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        return `${params[0].name}<br/>${params[0].seriesName}: ${formatTime(params[0].value)}`;
      }
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: function(value) {
          return formatTime(value);
        }
      }
    },
    series: [
      {
        name: '学习时长',
        type: 'bar',
        data: [3600, 4200, 3000, 3800, 4500, 5400, 3200],
        itemStyle: {
          color: '#409EFF'
        }
      }
    ]
  });
  
  // 学科分数对比图表
  const scoreChartInstance = echarts.init(scoreChart.value);
  scoreChartInstance.setOption({
    title: {
      text: '各学科得分',
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    radar: {
      indicator: [
        { name: '数学', max: 100 },
        { name: '物理', max: 100 },
        { name: '化学', max: 100 },
        { name: '语文', max: 100 },
        { name: '英语', max: 100 }
      ]
    },
    series: [
      {
        name: '学科得分',
        type: 'radar',
        data: [
          {
            value: [85, 78, 82, 90, 88],
            name: '当前得分',
            areaStyle: {
              color: 'rgba(230, 162, 60, 0.3)'
            },
            lineStyle: {
              color: '#E6A23C'
            },
            itemStyle: {
              color: '#E6A23C'
            }
          },
          {
            value: [80, 75, 80, 85, 82],
            name: '上期得分',
            lineStyle: {
              color: '#909399'
            },
            itemStyle: {
              color: '#909399'
            }
          }
        ]
      }
    ]
  });
  
  // 学习进度图表
  const progressChartInstance = echarts.init(progressChart.value);
  progressChartInstance.setOption({
    title: {
      text: '学习计划完成进度',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['计划进度', '实际进度'],
      bottom: 0
    },
    xAxis: {
      type: 'category',
      data: ['第1周', '第2周', '第3周', '第4周']
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value}%'
      },
      max: 100
    },
    series: [
      {
        name: '计划进度',
        type: 'line',
        data: [25, 50, 75, 100],
        lineStyle: {
          color: '#909399'
        },
        itemStyle: {
          color: '#909399'
        }
      },
      {
        name: '实际进度',
        type: 'line',
        data: [30, 55, 80, 95],
        lineStyle: {
          color: '#67C23A'
        },
        itemStyle: {
          color: '#67C23A'
        }
      }
    ]
  });
  
  // 错题分布图表
  const mistakesChartInstance = echarts.init(mistakesChart.value);
  mistakesChartInstance.setOption({
    title: {
      text: '错题学科分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center'
    },
    series: [
      {
        name: '错题数量',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 5, name: '数学' },
          { value: 4, name: '物理' },
          { value: 3, name: '化学' },
          { value: 2, name: '语文' },
          { value: 4, name: '英语' }
        ]
      }
    ]
  });
  
  // 监听窗口大小变化，重新调整图表大小
  window.addEventListener('resize', () => {
    timeChartInstance.resize();
    scoreChartInstance.resize();
    progressChartInstance.resize();
    mistakesChartInstance.resize();
  });
};

// 监听筛选条件变化
watch([timeRange, subjectFilter], () => {
  // 根据筛选条件更新数据
  console.log('筛选条件变化:', timeRange.value, subjectFilter.value);
  // 这里应该重新加载数据
});

// 组件挂载后初始化图表
onMounted(() => {
  // 延迟一下，确保DOM已经渲染
  setTimeout(() => {
    initCharts();
  }, 100);
});
</script>

<style lang="scss" scoped>
.statistics-container {
  padding: 20px;
  max-width: 90%;
  margin: 0 auto;
  
  .page-header {
    margin-bottom: 20px;
    
    h1 {
      margin: 0 0 10px;
      font-size: 24px;
      color: #303133;
    }
    
    p {
      margin: 0;
      color: #606266;
      font-size: 14px;
    }
  }
  
  .statistics-content {
    .statistics-filters {
      margin-bottom: 20px;
      display: flex;
      justify-content: flex-end;
      
      .filter-options {
        display: flex;
        gap: 10px;
        
        .el-select {
          width: 120px;
        }
      }
    }
    
    .statistics-overview {
      margin-bottom: 20px;
      
      .stat-card {
        height: 100%;
        display: flex;
        align-items: center;
        padding: 10px;
        margin-bottom: 20px;
        
        .stat-icon {
          width: 60px;
          height: 60px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 15px;
          color: #fff;
          font-size: 24px;
        }
        
        .stat-info {
          flex: 1;
          
          .stat-title {
            font-size: 14px;
            color: #909399;
            margin-bottom: 5px;
          }
          
          .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: #303133;
            margin-bottom: 5px;
          }
          
          .stat-trend {
            display: flex;
            align-items: center;
            font-size: 14px;
            
            &.up {
              color: #67C23A;
            }
            
            &.down {
              color: #F56C6C;
            }
            
            .el-icon {
              margin-right: 5px;
            }
          }
        }
      }
    }
    
    .statistics-charts {
      margin-bottom: 20px;
      
      .chart-card {
        margin-bottom: 20px;
        
        .chart-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          h3 {
            margin: 0;
            font-size: 16px;
            color: #303133;
          }
        }
        
        .chart-container {
          height: 300px;
        }
      }
    }
    
    .statistics-details {
      .details-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        h3 {
          margin: 0;
          font-size: 16px;
          color: #303133;
        }
      }
      
      .text-success {
        color: #67C23A;
      }
      
      .text-warning {
        color: #E6A23C;
      }
      
      .text-danger {
        color: #F56C6C;
      }
      
      .pagination-container {
        margin-top: 20px;
        display: flex;
        justify-content: center;
      }
    }
  }
}

@media (max-width: 768px) {
  .statistics-filters {
    justify-content: center !important;
  }
  
  .chart-container {
    height: 250px !important;
  }
}
</style> 